#include"PlaylistWriter.h" 

#include"Playlist.h"
#include"Song.h"

#include<stdio.h>
#include<QPointer>

void PlaylistWriter::write(Playlist *playlist, QString type, QString path){
	type = type.toLower();
	if(type == "m3u")
		writeM3u(playlist, path);
	else if(type == "xml")
		writeXml(playlist, path);
	else
		printf("Unknown playlist format: %s\n", type.toUtf8().data());
}

void PlaylistWriter::writeM3u(Playlist *playlist, QString path){
	QFile file(path);
	if(!file.open(QIODevice::WriteOnly)){
		printf("Couldn't write playlist to %s\n", path.toUtf8().data());
		return;
	}
	
	file.write("#EXTM3U\n\n");
	file.write("#Progression=");file.write(playlist->progressionText().toUtf8().data());file.write("\n");
	file.write("#Repeat=");file.write(playlist->repeatText().toUtf8().data());file.write("\n\n");
	
	for(uint i = 0; i < playlist->numSongs(); i++){
		QPointer<Song> song = playlist->song(i);
		if(!song)continue;
		QString text = "#EXTINF:" + QString().setNum(song->duration() / 100) + "," + song->artist() + " - " + song->title() + "\n";
		file.write(text.toUtf8().data());
		text = song->path() + "\n\n";
		file.write(text.toUtf8().data());
	}
	
	file.close();
}

void PlaylistWriter::writeXml(Playlist *playlist, QString path){
	QFile file(path);
	if(!file.open(QIODevice::WriteOnly)){
		printf("Couldn't write playlist to %s\n", path.toUtf8().data());
		return;
	}
	
	file.write("<?xml version=\"1.0\"?>\n");
	file.write("<root ");
	file.write("progression=\"");file.write(playlist->progressionText().toUtf8().data());file.write("\" ");
	file.write("repeat=\"");file.write(playlist->repeatText().toUtf8().data());file.write("\">\n");
	
	for(unsigned i = 0; i < playlist->numSongs(); i++){
		QPointer<Song> song = playlist->song(i);
		if(!song)continue;
		QString text = "";
		text.append("\t<song path=\"");	text.append(song->path());			text.append("\">\n");
		text.append("\t\t<title>");	text.append(song->title());			text.append("</title>\n");
		text.append("\t\t<artist>");	text.append(song->artist());			text.append("</artist>\n");
		text.append("\t\t<album>");	text.append(song->album());			text.append("</album>\n");
		text.append("\t\t<track>");	text.append(QString().setNum(song->track()));	text.append("</track>\n");
		text.append("\t\t<duration>");	text.append(QString().setNum(song->duration()));text.append("</duration>\n");
		text.append("\t</song>\n");
		file.write(text.toUtf8().data());
	}
	
	file.write("</root>\n");
	
	file.close();
}